<?php
use com\gdl\common\dataobject\common\ResultDO; 
use com\gdl\kq\interfaces\AttAppRepaircardServiceIf;
use com\gdl\kq\dataobject\repaircard\RepaircardDTO; 
use com\gdl\kq\dataobject\repaircard\RepaircardAllDTO;  
 
require(dirname(dirname(__FILE__)) ."/php_sdk-master/include.php");
use MagicCrypt\MagicCrypt;
/**
 * 考勤系统App补卡申请记录
 */
class api_AttAppRepaircardService extends api_Abstract implements AttAppRepaircardServiceIf{
	static public $photo = "http://ot7pftuwd.bkt.clouddn.com/jgg8s6pc_264rfqm9vgty5ae187f645c25.jpg";
	//App外出申请
	public function addRepaircard(RepaircardDTO $card){ 
		#接受参数
		$userId = $card->userId ? gdl_lib_BaseUtils::getStr($card->userId) : "";
		$platformId = $card->platformId ? gdl_lib_BaseUtils::getStr($card->platformId) : "";
		$unitId = $card->unitId ? gdl_lib_BaseUtils::getStr($card->unitId) : "";
		$data = $card->data ? $card->data : ""; 
		$cardId = $data['cardId']?$data['cardId']:"";
		
		# 实例化
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		if(empty($data)){$result->message = "请求网络失败，请检查手机网络状态"; return $result;}
		if(empty($cardId)){$result->message = "请选择需要补卡的班次"; return $result;}
		$insertCardData = $data;
		
		try{
			$cardModel = new model_attendance_approvalprocesscardreplacementrecord();
			$processService = new service_appprocess();# 获取审批流程规则
			$recordModel = new model_attendance_attendancerecord(); #考勤记录
			
			#查询审批流程
			$processResult = $processService->getMemberProcess($userId, $platformId, 3); #1:请假 2：外出 3：补卡 
			if(empty($processResult)){$result->message = "你还未加入考勤，请联系管理员添加"; return $result;}
			
			$insertCardData['processId'] = $processResult['id'] ? $processResult['id'] : 0; #审批流程id
			$insertCardData['proRule'] = $processResult['rules'] ? $processResult['rules'] : 0; #审批流程规则
			
			#查询考勤记录 往表里丢数据
			$recordWhere = "id={$cardId}";
			$recordFiled = "id,clockinNum,clockinDate,clockinType,agId,sureTime,sureDate";
			$recordInfo = $recordModel->selectOne($recordWhere, $recordFiled);
			
			#往补卡表里丢数据
			$insertCardData['agId'] = $recordInfo['agId'] ? $recordInfo['agId']:0;
			$insertCardData['num'] = $recordInfo['clockinNum'] ? $recordInfo['clockinNum']:1;
			$insertCardData['baseType'] = $recordInfo['clockinType'] ? $recordInfo['clockinType']:0;
			$insertCardData['sureTime'] = $recordInfo['sureTime'] ? $recordInfo['sureTime']:0;
			$insertCardData['replacementTime'] = $recordInfo['sureDate'] ? $recordInfo['sureDate']:0;
			
			$ret = $cardModel->insert($insertCardData);
			if($ret){
				#插入审批流程流程 申请id type  1：请假审批流程 2：外出审批流程 3：补卡审批流程
				$addApproval = $processService->insertApproval($userId, $processResult['rules'], $ret, 3);
				#修改考勤记录
				$retId = $ret?$ret:0;
				$reWhere = "id={$cardId}";
				$idResult = $recordModel->update($reWhere, ['noId'=>$retId]); 
				$result->message = "提交成功，等待审批";
				$result->code = 200;
				$result->data[] = [$ret];
			}else{
				$result->message = "网络异常，请检查手机网络";
			}
			
		}catch(Exception $ex){
			$result->message = $ex->getMessage();
		}
		 
        return $result; 
	}
	
    //App补卡记录列表
	public function repaircardList(RepaircardAllDTO $card){
		#接受参数
		$userId = $card->userId ? gdl_lib_BaseUtils::getStr($card->userId) : "";
		$platformId = $card->platformId ? gdl_lib_BaseUtils::getStr($card->platformId) : "";
		$unitId = $card->unitId ? gdl_lib_BaseUtils::getStr($card->unitId) : "";
		$offset = $card->offset ? gdl_lib_BaseUtils::getStr($card->offset) : 1;
		$num = $card->num ? gdl_lib_BaseUtils::getStr($card->num) : 10;
		$data = $card->data ? gdl_lib_BaseUtils::getStr($card->data) : ""; 
		$likeTitle = $data['likeTitle']?$data['likeTitle']:"";
		$status = $data['status']?$data['status']:0;#状态 0：全部 1：审批完成 2：审批中 3：撤销
		
		# 实例化
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		#分页
		if($offset=='0') $offset=1;
		$limit = ($offset - 1) * $num . "," . $num;
		$group = 'order by id desc limit '.$limit;
		
		#条件查询
		$where = "memberId={$userId} ";
			if(!empty($likeTitle)){
				$where.=" and (numberId like '%".$likeTitle."%' or reason like '%".$likeTitle."%') ";
			}
			if($status==1){
				$where.=" and (status=2 or status=3) ";
			}
			if($status==2){
				$where.=" and status=1 ";
			}
			if($status==3){
				$where.=" and status=4";
			}
		
		try{
			$cardModel = new model_attendance_approvalprocesscardreplacementrecord();
			$filed = "id,numberId,memberId,FROM_UNIXTIME(time, '%Y.%m.%d %H:%i') as cardTime,replacementTime,reason,status,FROM_UNIXTIME(createTime, '%Y.%m.%d %H:%i') as createTime";
			$list = $cardModel->select($where, $filed,$group)->items;
		
			if($list){
				# 遍历找审批人
				$list = $this->getMemberInfo($list, $userId);
				$listInfo['list'] = json_encode($list);
				$result->code = 200;
				$result->message = "获取成功";
				$result->data[]= $listInfo;
			}else{
				$result->code = 200;
				$result->message = "暂无数据";
			}
			
		}catch(Exception $ex){
			$result->message = $ex->getMessage();
		}
		 
        return $result;
	}
	//补卡详情
	public function repaircardInfo(RepaircardDTO $card){
		$userId = $card->userId ? gdl_lib_BaseUtils::getStr($card->userId) : "";
		$platformId = $card->platformId ? gdl_lib_BaseUtils::getStr($card->platformId) : "";
		$unitId = $card->unitId ? gdl_lib_BaseUtils::getStr($card->unitId) : "";
		$data = $card->data ? gdl_lib_BaseUtils::getStr($card->data) : "";
		$recordId = $data['recordId'] ? $data['recordId']:"";
		$cardId = $data['cardId'] ? $data['cardId']:"";
		
		# 实例化
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		#验证
		if(empty($platformId)){$result->message = "请选择平台"; return $result;}
		if(empty($recordId)){$result->message = "请选择外出记录"; return $result;}
		
		try{
			$cardModel = new model_attendance_approvalprocesscardreplacementrecord();
			$userModel = new model_attendance_member();
			
			$where = "id={$recordId}";
			$filed = "id,numberId,memberId,FROM_UNIXTIME(time, '%Y.%m.%d %H:%i') as cardTime,baseType,sureTime,replacementTime,reason,status,FROM_UNIXTIME(createTime, '%Y.%m.%d %H:%i') as createTime,images";
			$info = $cardModel->selectOne($where, $filed);
			if($info){
				#继续查用户
				$userWhere = "id={$info['memberId']}";
				$userFiled = "id,realName,photo,departmentId,unitId";
				$user = $userModel->selectOne($userWhere, $userFiled); #被审批用户
				$user['photo'] = $user['photo']?$user['photo']:self::$photo;
				$info['userInfo'] = $user; #被审批用户信息 
				$info['approvalUser'] = $this->getOneMember($recordId, $info['memberId']); #审批者信息
				
				$departmentId = $user['departmentId']?$user['departmentId']:$user['unitId'];
				$memberUserId = $user['id']?$user['id']:$info['memberId'];
				$memberUserInfo = $this->getMemberGroup($memberUserId,$departmentId,$platformId);
				$info['department'] = $memberUserInfo['department'];
				$info['agName'] = $memberUserInfo['agName'];
				$info['images'] = unserialize($info['images'])?unserialize($info['images']):[];
				$info['cardId'] = $cardId?$cardId:"";
				$info['today'] = $this->getToday(strtotime($info['replacementTime']));
				
				$recordIdInfo['data'] = json_encode($info);
				
				$result->message = "获取成功";
				$result->code = 200;
				$result->data[] = $recordIdInfo;
			}else{
				$result->message = "网络异常，请检查手机网络";
			}
		}catch(Exception $ex){
			$result->message = $ex->getMessage();
		}
		return $result;
	}
	
	//补卡催办
	public function repaircardUrge(RepaircardDTO $card){
		#接受参数
		$userId = $card->userId ? gdl_lib_BaseUtils::getStr($card->userId) : "";
		$platformId = $card->platformId ? gdl_lib_BaseUtils::getStr($card->platformId) : "";
		$unitId = $card->unitId ? gdl_lib_BaseUtils::getStr($card->unitId) : "";
		$data = $card->data ? gdl_lib_BaseUtils::getStr($card->data) : "";
		$recordId = $data['recordId'] ? $data['recordId']:""; 
		
		# 实例化
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		
		try{
			$msgModel = new model_attendance_messagerecord();
			$cardModel = new model_attendance_approvalprocesscardreplacementrecord();
			
			#找到审批人
			$approvalUser = $this->getOneMember($recordId, $userId);
			
			#催办时间间隔24小时只能催办一次
			$urgeWhere = "id={$recordId} and urge=1";
			$urge = $cardModel->selectOne($urgeWhere, 'id,urgeTime,urge');
			$allow = 24*60*60; # 24消息
			if(!empty($urge)){
				$nowTime = time();
				$urgeTime = $urge['urgeTime'] ? intval($urge['urgeTime']) :0;
				$diff = $nowTime-$urgeTime;
				if($diff<$allow){
					$result->message = "一天只能催办一次";
					return $result;
				}
			}
			
			#插入消息
			if($approvalUser){
				
				#遍历下级审批人 # type=2 我的审批
				for($i=0; $i<count($approvalUser); $i++){
					$msgModel->insert(['type'=>2,'recordId'=>$recordId,'approvalId'=>$approvalUser[$i]['approvalId'],'userId'=>$approvalUser[$i]['id'],'msgInfo'=>'待我审批','createTime'=>time()]);
				}
				#发送成功修改催办时间
				$cardModel->update("id={$recordId}",['urge'=>1,'urgeTime'=>time()]);
				
				$result->message = "催办提醒已发送";
				$result->code = 200; 
			}else{
				$result->message = "未找到相应审批人";
			}
		}catch(Exception $ex){
			$result->message = $ex->getMessage();
		}
		return $result;
	}
	
	//补卡撤销
	public function repaircardRevoke(RepaircardDTO $card){
		#接受参数
		$userId = $card->userId ? gdl_lib_BaseUtils::getStr($card->userId) : "";
		$platformId = $card->platformId ? gdl_lib_BaseUtils::getStr($card->platformId) : "";
		$unitId = $card->unitId ? gdl_lib_BaseUtils::getStr($card->unitId) : "";
		$data = $card->data ? gdl_lib_BaseUtils::getStr($card->data) : "";
		$recordId = $data['recordId'] ? $data['recordId']:""; 
		
		# 实例化
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		
		try{
			$cardModel = new model_attendance_approvalprocesscardreplacementrecord(); 
			$approvalModel = new model_attendance_approvalrecord();
			$msgModel = new model_attendance_messagerecord();
			
			#判断如果是已经通过的或撤销的则不再撤销
			$emptyWhere = "id={$recordId}";
			$emptyInfo = $cardModel->selectOne($emptyWhere, "id,status");
			if($emptyInfo['status']==2 || $emptyInfo['status']==3 || $emptyInfo['status']==4){
				$result->message = "该申请已通过或撤销无法再次撤销";
				return $result;
			}
			
			#先改变外出表的状态为撤回 '审核状态：1：审批中 2：通过 3：不通过 4：用户撤回'
			$cardWhere = "id={$recordId}";
			$cardRet = $cardModel->update($cardWhere, ['status'=>4]);
			
			#再将要所有的审批层级为可见的审批改为撤回 审批类型：1：请假 2：外出 3：补卡 4：其他',
			$approvalWhere = "coverMemberId={$userId} and recordId={$recordId} and type=2"; // and isShow=1
			$approvalRet = $approvalModel->update($approvalWhere, ['adopt'=>4]);
			
			#找审批人向他推送一条消息 告知已撤回
			$approvalUser = $this->getOneMember($recordId, $userId);
			
			if($approvalUser){
				for($i=0; $i<count($approvalUser); $i++){
					$msgModel->insert(['type'=>4,'recordId'=>$recordId,'approvalId'=>$approvalUser[$i]['approvalId'],'userId'=>$approvalUser[$i]['id'],'msgInfo'=>'待我审批的用户撤回','createTime'=>time()]);
				}
			}
			
			$result->message = "撤回成功";
			$result->code =200;
			
		}catch(Exception $ex){
			$result->message = $ex->getMessage();
		}
		
		return $result;
	}
	
	//补卡申请页详情
	public function cardInfo(RepaircardDTO $card){
		#接受参数
		$userId = $card->userId ? gdl_lib_BaseUtils::getStr($card->userId) : "";
		$platformId = $card->platformId ? gdl_lib_BaseUtils::getStr($card->platformId) : "";
		$unitId = $card->unitId ? gdl_lib_BaseUtils::getStr($card->unitId) : "";
		$data = $card->data ? gdl_lib_BaseUtils::getStr($card->data) : "";
		$recordId = $data['recordId'] ? $data['recordId']:"";
		
		# 实例化
		$result = new ResultDO();
        $result->success = true;
        $result->code = 400; 
        $result->data = [];
		
		try{
			$ret = [];
			$recordModel = new model_attendance_attendancerecord(); #考勤记录
			$recordWhere = "id={$recordId}";
			$recordFiled = "id,clockinDate,clockinType,sureTime,sureDate";
			$recordInfo = $recordModel->selectOne($recordWhere, $recordFiled);
			
			if($recordInfo){
				$ret['cardId'] = $recordInfo['id']?$recordInfo['id']:0;
				if($recordInfo['clockinDate']){
					$ret['today'] = $this->getToday(strtotime($recordInfo['clockinDate']));
				}else{
					$ret['today'] = $this->getToday(time()); #没有就获取当天的
				}
				$ret['endTime'] = $recordInfo['sureTime']; #打卡班次时间
				$ret['sureDate'] = $recordInfo['sureDate']; #打卡班次
				$ret['type'] = $recordInfo['clockinType']; # 1：上班 2：下班
				$result->message = "获取成功";
				$result->code = 200;
				$result->data[] = $ret;
				
			}else{
				$result->message = "网络异常，请检查手机网络";
			}
			
			
		}catch(Exception $ex){
			$result->message = $ex->getMessage();
		}
		return $result;
	}
	// atd_attendance_record 时间段 isGo =2 查询member=userID agId=当前考勤组 时间段
	//遍历找审批人 1:请假 2：外出 3：补卡
	private function getMemberInfo($list, $userId, $type=3){ 
		$cardModel = new model_attendance_approvalprocesscardreplacementrecord(); 
		$userModel = new model_attendance_member();
		$leftJoin = [
			'atd_approve_record as r' => 'atd_approval_process_card_replacement_record.id=r.recordId', 
		];
		$where = " r.id= (select MAX(rs.level) from atd_approve_record as rs where rs.isShow=1 and rs.type={$type}) and r.adopt=1 "; #可见并且最大审批层 and coverMemberId=zijiand MAX(r.level) r.isShow=1 and r.type=1 and 
		
		for($i=0; $i<count($list); $i++){
			#设置审批用户
			$list[$i]['approvalUser'] = [];
			#是否查询 如果审批通过不再查询数据库 状态为1为审批中才查询用户
			if($list[$i]['status']==1){
				#查找 审核状态为待审批3 被审批人为当前审批人 记录id为当前记录id 并且显示的审批分层id
				$where = " r.id= (select id from atd_approve_record as rs where rs.isShow=1 and rs.type={$type} and rs.adopt=1 and rs.coverMemberId={$userId} and rs.recordId={$list[$i]['id']} GROUP BY level DESC LIMIT 1) ";
				$recordInfo = $cardModel->select($where, 'r.id,r.coverMemberId,r.memberId,r.adopt', '', '', $leftJoin)->items;
				if($recordInfo){
					for($j=0; $j<count($recordInfo); $j++){
						$userWhere = "id={$recordInfo[$j]['memberId']}";
						$userFiled = "id,realName";
						$userInfo = $userModel->selectOne($userWhere, $userFiled);
						$list[$i]['approvalUser'][] = $userInfo;
					}
				}
			}
		}
		
		return $list ? $list:[];
	}
	
	//找单个审批人 外出申请id
	private function getOneMember($recordId,$userId, $type=3){
		
		$user = [];
		
		$cardModel = new model_attendance_approvalprocesscardreplacementrecord(); 
		$userModel = new model_attendance_member();
		
		$leftJoin = [
			'atd_approve_record as r' => 'atd_approval_process_card_replacement_record.id=r.recordId', 
		];
		$where = " r.id= (select MAX(rs.level) from atd_approve_record as rs where rs.isShow=1 and rs.type={$type}) and r.adopt=1 "; #可见并且最大审批层 and coverMemberId=zijiand MAX(r.level) r.isShow=1 and r.type=1 and 
		
		#查找 审核状态为待审批3 被审批人为当前审批人 记录id为当前记录id 并且显示的审批分层id
		$where = " r.id= (select id from atd_approve_record as rs where rs.isShow=1 and rs.type={$type} and rs.adopt=1 and rs.coverMemberId={$userId} and rs.recordId={$recordId} GROUP BY level DESC LIMIT 1) ";
		$recordInfo = $cardModel->select($where, 'r.id,r.coverMemberId,r.memberId,r.adopt', '', '', $leftJoin)->items;
		
		if($recordInfo){
			for($j=0; $j<count($recordInfo); $j++){
				$userWhere = "id={$recordInfo[$j]['memberId']}";
				$userFiled = "id,realName";
				$userInfo = $userModel->selectOne($userWhere, $userFiled);
				$userInfo['approvalId'] = $recordInfo[$j]['id'];
				$user[] = $userInfo;
			}
		} 
		return $user;
	}
	// 找审批人部门考勤组相关
	private function getMemberGroup($userId='', $departmentId='',$platformId=''){
		$info = ['department'=>'暂无部门', 'agName'=>'无考勤组'];
		if(empty($userId)){return false;}
		
		$unitsModel = new model_lhbase_units();
		$groupUserModel = new model_attendance_attendancegroupuser();
		$groupModel = new model_attendance_attendancegroup();
		#查被审批人的部门和考勤组
		$unitsWhere = "id={$departmentId}";
		$unitInfo = $unitsModel->selectOne($unitsWhere, 'id,unitName');
		$info['department'] = $unitInfo['unitName']?$unitInfo['unitName']:"暂无部门";
		
		#找该用户考勤组
		$memberWhere = "memberId={$userId} and type=1 and platformId={$platformId} "; #  and status=0 #目前做的物理删除该字段暂未用到 type1:参与考勤人员 2：无需参与考勤人员
		$memberGroup = $groupUserModel->selectOne($memberWhere, '*');
		$agId = $memberGroup['agId'] ? $memberGroup['agId'] : 0; #考勤组id
		#查找
		$agWhere = "id={$agId}";
		$agInfo = $groupModel->selectOne($agWhere, 'id,title');
		$info['agName'] = $agInfo['title'] ? $agInfo['title'] : "无考勤组";
		
		return $info;
	}
	//根据日期计算星期几
	private function getToday($time){
		$i=0;
		$weekarray = array("日","一", "二", "三", "四", "五", "六");
		$oneD = 24 * 60 * 60;
		return "星期" . $weekarray[date("w", $time + $oneD * $i)];
	}
}

